const express = require('express')
const { attendanceSchema } = require('../../models/attendance')
const { student, teacher } = require('../../models/User')
const { curriculum } = require('../../models/curriculum')
const router = express.Router();
const moment = require('moment')

// 签到
router.post('/sign', (req, res) => {
    curriculum.findOne({ _id: req.body.curriculumId }).then(async result => {
        console.log(result);
        const start = moment((moment().format('YYYY-MM-DD ')) + result.start_time).unix()
        const end = moment((moment().format('YYYY-MM-DD ')) + result.end_time).unix()
        const fifteen = start + (15 * 60 * 1000)
        const now = moment().unix()
        let state = null

        if (now >= end) {
            state = 2
        } else if (now > start && now < fifteen) {
            state = 1
        } else {
            state = 0
        }
        const student_name = (await new Promise((resolve, reject) => student.findOne({ _id: req.body.userId }).then(res => resolve(res)).catch(err => reject(err)))).name
        const teacher_name = (await new Promise((resolve, reject) => teacher.findOne({ _id: req.body.teacherId }).then(res => resolve(res)).catch(err => reject(err)))).name
        console.log();
        new attendanceSchema({
            userId: req.body.userId,
            curriculumId: req.body.curriculumId,
            teacherId: req.body.teacherId,
            student_name,
            teacher_name,
            state
        }).save().then(() => {
            res.json({
                status: 200,
                msg: '签到成功'
            })
        })

    })
})

// 获取该老师下的所有学生的签到记录
router.get('/teacher/:id', (req, res) => {
    attendanceSchema.find({ teacherId: req.params.id }).then(result => {
        res.json({
            status: 200,
            data: result
        })
    })
})

// 获取该学生的所有签到记录
router.get('/student/:id', (req, res) => {
    attendanceSchema.find({ userId: req.params.id }).then(result => {
        res.json({
            status: 200,
            data: result
        })
    })
})

// 删除一条签到记录
router.delete('/:id', (req, res) => {
    attendanceSchema.deleteOne({ _id: req.params.id }).then(() => {
        res.json({
            status: 200,
            msg: '删除成功'
        })
    })
})

module.exports = router;